package no.nordicsemi.android.dfuupdate.scanner;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.ParcelUuid;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;

import no.nordicsemi.android.dfuupdate.R;
import no.nordicsemi.android.dfuupdate.dfu.SelectedFileActivity;
import no.nordicsemi.android.support.v18.scanner.BluetoothLeScannerCompat;
import no.nordicsemi.android.support.v18.scanner.ScanCallback;
import no.nordicsemi.android.support.v18.scanner.ScanFilter;
import no.nordicsemi.android.support.v18.scanner.ScanResult;
import no.nordicsemi.android.support.v18.scanner.ScanSettings;

public class ScanBatchActivity extends AppCompatActivity{


    private final static long SCAN_DURATION = 60000;
    private final static String PARAM_UUID = "param_uuid";
    private final static int REQUEST_PERMISSION_REQ_CODE = 34;
    private BluetoothAdapter bluetoothAdapter;
    private BtchDeviceListAdapter deviceListAdapter;
    private final Handler handler = new Handler();
    private Button scanButton;
    private View permissionRationale;
    private ParcelUuid uuid;
    private  boolean scanning = false;
    private SearchView searchView;
    public static String keyWord;
    private TextView Count;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_batch);
        Log.d("KEYWORDDD", String.valueOf(keyWord == null));
        setGui();
        //addBoundDevices();
        if(savedInstanceState == null) {
            startScan();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.select_option, menu);
        menu.findItem(R.id.select_all).setVisible(true);
        menu.findItem(R.id.select_oppo).setVisible(true);
        menu.findItem(R.id.update).setVisible(true);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(final MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                break;
            case R.id.select_all: {
                // TODO 全选操作
                List<ExtendedBluetoothDevice> devices = deviceListAdapter.getDevices();
                for(ExtendedBluetoothDevice device : devices){
                    deviceListAdapter.editMap(device.device.getAddress(),true);
                }
                deviceListAdapter.notifyDataSetChanged();
                Count.setText("count : " + deviceListAdapter.getItemCount() + ", selected : " + deviceListAdapter.getMapCount());
                return true;
            }
            case R.id.select_oppo: {
                // TODO 反选操作
                List<ExtendedBluetoothDevice> devices = deviceListAdapter.getDevices();
                for(ExtendedBluetoothDevice device : devices){
                    if(deviceListAdapter.findMap(device.device.getAddress())) {
                        deviceListAdapter.mapRemove(device.device.getAddress());
                    } else {
                        deviceListAdapter.editMap(device.device.getAddress(),true);
                    }

                }
                deviceListAdapter.notifyDataSetChanged();
                Count.setText("count : " + deviceListAdapter.getItemCount() + ", selected : " + deviceListAdapter.getMapCount());
                return true;
            }
            case R.id.update: {
                // TODO 下一步批量升级=> 选择升级文件
                //Toast.makeText(ScanBatchActivity.this, "批量升级操作", Toast.LENGTH_SHORT).show();
                if(deviceListAdapter.getSelectedDevices().size() == 0) {
                    Toast.makeText(ScanBatchActivity.this, "未选中升级设备！", Toast.LENGTH_LONG).show();
                }
                else {
                    Intent intent = new Intent(ScanBatchActivity.this, SelectedFileActivity.class);
                    Bundle bundle = new Bundle();
                    ArrayList<String> selected = new ArrayList<String>();
                    for(ExtendedBluetoothDevice dev : deviceListAdapter.getDevices()) {
                        if(deviceListAdapter.findMap(dev.device.getAddress())) {
                            BleDev temp = new BleDev(dev.device.getName(),dev.device.getAddress());
                            selected.add(JSON.toJSONString(temp));
                        }
                    }
                    bundle.putStringArrayList("SELECTED_DEVICES", selected);
                    intent.putExtras(bundle);
                    startActivity(intent);
                    //finish();
                    stopScan();
                    return true;
                }

            }
        }
//        if (android.R.id.home == (item.getItemId())) {
//            onBackPressed();
//            return true;
//        }
        return super.onOptionsItemSelected(item);
    }

    protected void setGui() {

        final Toolbar toolbar  = findViewById(R.id.toolbar_actionbar);
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);



        final ListView listView = (ListView) findViewById(R.id.batch_list);
        listView.setEmptyView((findViewById(android.R.id.empty)));

        listView.setAdapter(deviceListAdapter = new BtchDeviceListAdapter());

        listView.setOnItemClickListener((parent, view, position, id) -> {
//            stopScan();
////            final ExtendedBluetoothDevice d = (ExtendedBluetoothDevice) deviceListAdapter.getItem(position);
////            Log.d("device click", d.device.getName() + ":" + d.device.getAddress());
////            // connect to selected device
////            if(d == null) return;
////            //////////////////////////////////////////////
////            Intent intent = new Intent(ScanBatchActivity.this, DeviceControlActivity.class);
////            Bundle bundle = new Bundle();
////            bundle.putString("extra_device_name", d.device.getName());
////            bundle.putString("extra_mac_address", d.device.getAddress());
////            intent.putExtras(bundle);
////            Log.d("start activity", "about to device control");
////            startActivity(intent);
////            //////////////////////////////////////////////

            // TODO 多选操作
            final ExtendedBluetoothDevice d = (ExtendedBluetoothDevice) deviceListAdapter.getItem(position);
            final String mac = d.device.getAddress();
            if(deviceListAdapter.findMap(mac)) {
                deviceListAdapter.mapRemove(mac);
            } else
                deviceListAdapter.editMap(mac,true);
            deviceListAdapter.notifyDataSetChanged();

        });
        listView.setTextFilterEnabled(true);

        Count = (TextView) findViewById(R.id.bat_count);

        scanButton = (Button) findViewById(R.id.action_cancel);
        scanButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(v.getId() == R.id.action_cancel) {
                    if(scanning) {
                        stopScan();
                    } else {
                        startScan();
                    }
                }
            }
        });

        searchView = (SearchView) findViewById(R.id.bth_searchView);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public boolean onQueryTextChange(String newText) {
                Log.d("QUERY" ,"NEWTEXT =" + newText);
                if(!TextUtils.isEmpty(newText)) {
                    keyWord = newText.toUpperCase();
                    Log.d("ListVIEW", "SetFIlterText_" + keyWord);
                    deviceListAdapter.filtList(newText.toUpperCase());
                    Count.setText("count : " + deviceListAdapter.getItemCount());

                } else {
                    //listView.clearTextFilter();
                    keyWord = "";
                    deviceListAdapter.filtList("");
                    Count.setText("count : " + deviceListAdapter.getItemCount());
                }
                return false;
            }


        });




    }



    private void startScan() {

        deviceListAdapter.clearDevices();
        scanButton.setText("Cancel");

        final BluetoothLeScannerCompat scanner = BluetoothLeScannerCompat.getScanner();
        final ScanSettings settings = new ScanSettings.Builder()
                .setLegacy(false)
                .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).setReportDelay(1000)
                .setUseHardwareBatchingIfSupported(false).build();
        final List<ScanFilter> filters = new ArrayList<>();
        filters.add(new ScanFilter.Builder().setServiceUuid(uuid).build());
        scanner.startScan(filters,settings,scanCallback);

        scanning = true;
        handler.postDelayed(() -> {
            if(scanning) {
                stopScan();
            }
        },SCAN_DURATION);
    }


    private void stopScan() {
        if(scanning) {
            scanButton.setText("Scan");
            final BluetoothLeScannerCompat scanner = BluetoothLeScannerCompat.getScanner();
            scanner.stopScan(scanCallback);

            scanning = false;
        }
    }

    private ScanCallback scanCallback = new ScanCallback() {
        @Override
        public void onScanResult(final int callbackType, @NonNull final ScanResult result) {

        }

        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void onBatchScanResults(@NonNull final List<ScanResult> results) {
            deviceListAdapter.update(results);
            if(deviceListAdapter.getMapCount() == 0)
                Count.setText("count : " + deviceListAdapter.getItemCount());
            else
                Count.setText("count : " + deviceListAdapter.getItemCount() + ", selected : " + deviceListAdapter.getMapCount());

        }

        @Override
        public void onScanFailed(final int errorCode) {
            // should never be called
        }
    };

    private void addBoundDevices() {
        final Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices();
        deviceListAdapter.addBondedDevices(devices);
    }

    @Override
    protected void onResume() {
        Log.d("SBR", "onResume");
        Log.d("KEY", String.valueOf(keyWord));
        super.onResume();
        if(!scanning)
            startScan();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopScan();
    }


}

